import json
import os

from markdown.api_doc_model import ApiDoc
from markdown.template import get_default_apifox_template, get_dir_template

"""
Author: Gaoqiang Du
Description：将markdown转成apifox文件程序主入口
Time: 2022/4/18 13:58
"""


def transform_one_markdown_to_apifox(md_path, ):
    doc = ApiDoc()
    parser = doc.parser_markdown()
    next(parser)

    with open(md_path, "r", encoding="utf8") as f:
        for line in f:
            status = parser.send(line.strip())
            if not status:
                break

    return doc.format_to_template()


def transform_all_markdown_to_apifox(name, root_dir, save_path=None,
                                     ignore_dirs=None, typing="project"):
    ignore_dirs = ignore_dirs or []
    list_dir = os.listdir(root_dir)
    if typing == "project":
        api_json = get_default_apifox_template()
        api_json["info"]["name"] = name
        for i in list_dir:
            path = os.path.join(root_dir, i)
            if os.path.isdir(path) and i not in ignore_dirs:
                api_json["apiCollection"][0]["items"].append(
                    transform_all_markdown_to_apifox(
                        i, path, typing="dir"
                    )
                )
    else:
        api_json = get_dir_template()
        api_json["name"] = name
        for i in list_dir:
            path = os.path.join(root_dir, i)
            if i.endswith(".md"):
                api_json["items"].append(
                    transform_one_markdown_to_apifox(path)
                )
            elif os.path.isdir(path):
                api_json["items"].append(
                    transform_all_markdown_to_apifox(i, path, typing="dir")
                )

    if save_path:
        with open(save_path, "w", encoding="utf8") as f:
            json.dump(api_json, f)

    return api_json


if __name__ == '__main__':
    dir_path = r"API参考"
    save_path = r"markdown_xx.json"
    print(transform_all_markdown_to_apifox("project_name", dir_path, save_path, ))
